package com.xhorse.lockplatform.comm.mvc;

import com.xhorse.lockplatform.comm.enums.ResultEnum;
import com.xhorse.lockplatform.comm.model.ResultUtil;
import com.xhorse.lockplatform.comm.util.JsonSupport;
import com.xhorse.lockplatform.comm.util.LogUtil;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.springframework.validation.BindingResult;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 抽象的公共控制器
 *
 * @author Tom
 */

public abstract class AbstractCallbackController implements JsonSupport {

    protected void simpleSuccess(HttpServletResponse response) throws Exception {
        responseJson(response, ResultUtil.success());
    }

    protected void simpleSuccess(HttpServletResponse response, Object data) throws Exception {
        responseJson(response, ResultUtil.success(data));
    }

    protected void simpleFailed(HttpServletResponse response) throws Exception {
        responseJson(response, ResultUtil.failed());
    }

    protected void simpleFailed(HttpServletResponse response, String errorMsg) throws Exception {
        responseJson(response, ResultUtil.failed(ResultEnum.FAILED.getCode(), errorMsg));
    }

    protected void responseJson(HttpServletResponse response, Object obj) throws IOException {
        MAPPER.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
        MAPPER.writeValue(response.getOutputStream(), obj);
    }

    /**
     * 检查参数合法性
     *
     * @param errors
     * @param response
     * @return
     */
    protected boolean checkParam(BindingResult errors, HttpServletResponse response) throws Exception {
        if (!errors.hasErrors()) {
            return false;
        }
        String errorMsg = errors.getFieldError().getDefaultMessage();
        LogUtil.getLogger().error(errorMsg);
        simpleFailed(response, errorMsg);
        return true;
    }
}

